#include "OCMain/FileUtil.h"
#include "OCMain/Environment.h"
#include "OCMain/Log.h"
#include "OCServer/MapManager.h"
#include "OCServer/ServerUtil.h"

using namespace OCPP;

template <typename T>
inline std::vector<T> getYmlVec(const YAML::Node& node)
{
	std::vector<T> vec;
	if (node.Type() == YAML::NodeType::Sequence)
	{
		try {
			for (const auto& c : node)
			{
				vec.push_back(c.as<T>());
			}
		}
		catch (...) {}
	}

	return vec;
}


void init()
{
	String yamlFileName = Singleton(Environment).getAppPath() + "config/OCPP_ControllerMapServer.yml";
	try {
		YAML::Node node = YAML::LoadFile(yamlFileName);
		for (const auto& child : node)
		{
			const auto& map = child.second;
			String ext = getYmlValue<String>(map, "ext", "");
			String fileName = getYmlValue<String>(map, "path", "");
			bool bRegisterMap = Singleton(MapManager).registerMap(fileName, ext);
			bool bRegisterCacher = false;
			YAML::Node cache = map["cache"];
			String cachePath;
			if (cache.IsDefined())
			{
				String url = getYmlValue<String>(cache, "url", "");
				cachePath = getYmlValue<String>(cache, "path", "");
				StringVector subdomains;
				YAML::Node subdomainsNode = cache["subdomains"];
				if (subdomainsNode.Type() == YAML::NodeType::Sequence)
				{
					subdomains = getYmlVec<String>(subdomainsNode);
				}
				bRegisterCacher = Singleton(MapManager).registerCacher(fileName, ext,
					url, cachePath, subdomains);
			}

			if (!bRegisterMap && !bRegisterCacher)
			{
				OCPP_LOG_ERROR << fileName << " not found.\n";
			}
			else
			{
				StringStream logStream;
				logStream << fileName << " regitster ";
				if (bRegisterMap)
				{
					logStream << "MapServer";
					if(bRegisterCacher)
						logStream << ",MapCache";
				}
				else if (bRegisterCacher)
				{
					logStream << "MapCache";
				}
				OCPP_LOG_INFO << logStream.str() << "\n";
			}

		}
	}
	catch (const YAML::Exception& e) {
		LOG_ERROR << e.msg << "\n";
	}
}

void release()
{
}